import React, { Component } from 'react'
import { connect } from 'react-redux'
import actionCreator from '@/store/actionCreator'
import { USERCHANGE } from '@/store/actionType'
import {
  // detailsReq, 
  collectReq
} from '@/utils/request'
import * as ReactMarkdown from 'react-markdown'
import CodeBlock from './CodeBlock'
// import markdownIt from 'markdown-it'
// import hljs from 'highlight.js'
// import 'highlight.js/styles/monokai-sublime.css'
// import './detailsCode.css'

import { tagColor } from '@/utils/method'
import { PageHeader, Layout, Tag, Button, Tooltip } from 'antd'
import { StarFilled, StarOutlined } from '@ant-design/icons'
import CommentItem from './comment'
const { Content } = Layout

// var md = new markdownIt({
//   html: false,        // Enable HTML tags in source
//   xhtmlOut: false,        // Use '/' to close single tags (<br />).
//   // This is only for full CommonMark compatibility.
//   breaks: false,        // Convert '\n' in paragraphs into <br>
//   langPrefix: 'language-',  // CSS language prefix for fenced blocks. Can be
//   // useful for external highlighters.
//   linkify: false,        // Autoconvert URL-like text to links
//   // Enable some language-neutral replacement + quotes beautification
//   typographer: false,
//   // Double + single quotes replacement pairs, when typographer enabled,
//   // and smartquotes on. Could be either a String or an Array.
//   //
//   // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
//   // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
//   quotes: '“”‘’',
//   // Highlighter function. Should return escaped HTML,
//   // or '' if the source string is not changed and should be escaped externally.
//   // If result starts with <pre... internal wrapper is skipped.
//   highlight: function (str, lang) {
//     if (lang && hljs.getLanguage(lang)) {
//       try {
//         return '<pre class="hljs"><code>' +
//           hljs.highlight(lang, str, true).value +
//           '</code></pre>';
//       } catch (__) { }
//     }
//     return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
//   }
//   // highlight: function (code) {
//   //   return hljs.highlightAuto(code).value;
//   // }
// });
// marked.setOptions({
//   renderer: new marked.Renderer(),
//   gfm: true,
//   pedantic: false,
//   sanitize: false,
//   tables: true,
//   breaks: true,
//   smartLists: true,
//   smartypants: true,
//   highlight: function (code) {
//     return hljs.highlightAuto(code).value;
//   }
// })

const mapStateToProps = (state, ownProps) => {
  return {
    collectList: state.getIn(['user', 'obj', 'collectList']),
    blogList: state.getIn(['blog', 'allArticles']).filter(item => item._id === ownProps.match.params.id)
  }
}
const mapDispatchToProps = {
  // promise中间件
  getCollect: (data) => {
    return collectReq(data).then(res => {
      return {
        type: USERCHANGE,
        payload: res.result
      }
    })
  },
  getAllArticle: actionCreator.getAllArticle,
  setBreadList: actionCreator.setBreadList
}

@connect(mapStateToProps, mapDispatchToProps)
class Details extends Component {
  constructor(props) {
    super(props)
    this.state = {
      tooltipText: '',
      visible: false
    }
  }

  componentDidMount() {
    this.props.setBreadList(['博客', '详情'])
    this.props.getAllArticle()
  }

  render() {
    const id = this.props.match.params.id
    const { tooltipText, visible } = this.state
    const { collectList, blogList } = this.props
    const blog = blogList[0]
    let tags = blog ? [...blog.tags] : []
    tags.splice(0, 1)
    return (
      <>
        {
          blog ?
            <div>
              <PageHeader
                className="site-page-header-responsive"
                onBack={() => window.history.back()}
                tags={tags.map((item, i) => (
                  <Tag color={tagColor()} key={i}>{item}</Tag>
                ))}
                title={blog.title}
                subTitle={blog.author}
                extra={[
                  <Tooltip key="star" placement="topLeft" visible={visible} title={tooltipText}>
                    <Button shape="circle"
                      onClick={() => this.setCollect(collectList, blog)}
                      icon={collectList && collectList.some(item => item._id === id) ? <StarFilled style={{ color: '#ffd700' }} /> : <StarOutlined />}>
                    </Button>
                  </Tooltip>
                ]}
              >
                <Content>
                  <div>
                    <ReactMarkdown
                      // let html=marked(mdcontent)//渲染成html
                      // source={md.render(blog.text)}
                      source={blog.text}
                      renderers={{
                        code: CodeBlock
                      }}
                      // 如果您处于受信任的环境中，并且想解析和呈现HTML，则需要使用该html-parser插件。对于默认配置，请导入react-markdown/with-html而不是默认值：
                      escapeHtml={false}
                    />
                  </div>
                  {/* 评论 */}
                  <CommentItem id={id} commentNum={blog.commentNum} />
                </Content>
              </PageHeader>
              <div>

              </div>

            </div> : <div></div>
        }
      </>
    )
  }

  setCollect = (collectList, blog) => {
    const token = sessionStorage.getItem('bloger')
    const { getCollect } = this.props
    const id = this.props.match.params.id
    if (token) {
      if (collectList && collectList.some(item => item._id === id)) {//已点赞
        getCollect({ collectList: collectList.filter(item => item._id !== id) }).then(() => {
          // 文字提示
          this.setState({ visible: true, tooltipText: "取消收藏" }, () => {
            setTimeout(() => {
              this.setState({ visible: false, tooltipText: '' })
            }, 1000)
          })
        })
      } else {//未点赞
        getCollect({ collectList: [...collectList, blog] }).then(() => {
          this.setState({ visible: true, tooltipText: "收藏成功" }, () => {
            setTimeout(() => {
              this.setState({ visible: false, tooltipText: '' })
            }, 1000)
          })
        })
      }
    }
  }
}
export default Details
